package main

import (
	"encoding/json"
	"fmt"
	apps_v1 "k8s.io/api/apps/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/clientcmd"
	"os"
	"time"
)

func main() {
	namespace := "default"
	home, _ := os.UserHomeDir()
	kubeconfig := home + "/.kube/config"
	fmt.Println(1111, kubeconfig)
	cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
	clientset, err := kubernetes.NewForConfig(cfg)
	if err != nil {
		panic(err)
	}
	fmt.Println(1111111111)
	stopCh := make(chan struct{})
	defer close(stopCh)
	shardInformerFactory := informers.NewSharedInformerFactory(clientset, time.Minute)

	dpInformer := shardInformerFactory.Apps().V1().Deployments()

	sharedIndexInformer := dpInformer.Informer()

	sharedIndexInformer.AddEventHandler(
		cache.ResourceEventHandlerFuncs{
			AddFunc:    onAdd,
			UpdateFunc: onUpdate,
			DeleteFunc: onDelete,
		})
	fmt.Println(22222222)
	lister := dpInformer.Lister()

	shardInformerFactory.Start(stopCh) // 启动informer
	fmt.Println(33333333)
	if !cache.WaitForCacheSync(stopCh, sharedIndexInformer.HasSynced) {
		return
	}
	fmt.Println(44444444)
	dps, err := lister.Deployments(namespace).List(labels.Everything())
	if err != nil {
		panic(err)
	}
	fmt.Println(555555555)
	for _, dp := range dps {
		fmt.Printf("%s\r\n", dp.Name)
	}
	<-stopCh // 取值
}

func onAdd(obj interface{}) {
	dp := obj.(*apps_v1.Deployment)
	if dp.Name == "busybox" {
		fmt.Println("onAdd...")
		data, _ := json.Marshal(dp)
		fmt.Printf("data: %v \n", string(data))
		fmt.Println("==================")
	}

}

func onUpdate(old, new interface{}) {
	oldDp := old.(*apps_v1.Deployment)
	newDp := new.(*apps_v1.Deployment)
	if oldDp.Name == "busybox" {
		fmt.Println("onUpdate...")

		replicas1 := *oldDp.Spec.Replicas
		env1 := oldDp.Spec.Template.Spec.Containers[0].Env
		replicas2 := *newDp.Spec.Replicas
		env2 := newDp.Spec.Template.Spec.Containers[0].Env
		fmt.Printf("老的数据: 副本数：%v 环境变量：%v\n\n", replicas1, env1)
		fmt.Printf("新的数据: 副本数：%v 环境变量：%v \n", replicas2, env2)
		/*
			data1, _ := json.Marshal(*oldDp)
			data2, _ := json.Marshal(*newDp)
			fmt.Printf("old data: %v \n", string(data1))
			fmt.Printf("new data: %v \n", string(data2))

		*/
		fmt.Println("==================")
	}
}

func onDelete(obj interface{}) {
	fmt.Println("onDelete...")
	dp := obj.(*apps_v1.Deployment)
	if dp.Name == "busybox" {
		fmt.Printf("onDelete:%s \n", dp.Name)
	}

}
